// index.js
// 获取应用实例
const app = getApp()
import Dialog from "@vant/weapp/dialog/dialog"
let Request = require("../../utils/ajax"); //导入模块
const {
  baseUrl, appid
} = require("../../config.js");
Page({
  data: {
    isItinerary: '',//是否有登记行程
    isHealthCode: false,
    isCheckbox: true,
    errInfo: false,//未申请健康码的显示
    showCode: false,
    showList: false,//您本人的身份信息的显示
    disabled: false,
    errInfoTitle: false,//
    healthCodeButton: true,
    phone: '',//手机号
    verificationCode: '',//手机验证码
    luminance: 0.5,
    list: [],
    personNumber: '',//身份证
    personNumberNew: '',
    openId: '',
    onlyinp:true,
    code: '',
    errText: '确定',
    showconfirm:false,//隐私政策是否弹出
  },
  onLoad(options) {
    // console.log(options.isUnbind);
    console.log(options.phone);
    if(options.showList){
      var show = (options.showList==1)
      console.log(show);
      if(show){
        this.setData({
          errInfo:true,
          phone:options.phone,
          onlyinp:false,
          healthCodeButton:false,
        })
        this.getVerificationCode()
        // this.isHealthCodeAndItineraryInfo()
      }

    }
    // 2022/2/9
    this.getScreenBrightness()
    if(!options.isUnbind){
      if (app.globalData.openId) {
        // 加上切换的判断条件
        if (app.globalData.isItineraryInfoByOpenId == true &&!app.globalData.switchId) {
          this.getItineraryCodeNew()
        }
      } else {
        // 所以此处加入 callback 以防止这种情况
        app.openIdParamCallback = data => {
          app.globalData.openId = data.openId
          app.globalData.isItineraryInfoByOpenId = data.isItineraryInfoByOpenId
          if (app.globalData.isItineraryInfoByOpenId == true&&!app.globalData.switchId) {
            this.getItineraryCodeNew()
          }
        }
      }
    }
/* 
    if (app.globalData.openId) {
      // 加上切换的判断条件
      if (app.globalData.isItineraryInfoByOpenId == true &&!app.globalData.switchId) {
        this.getItineraryCodeNew()
      }
    } else {
      // 所以此处加入 callback 以防止这种情况
      app.openIdParamCallback = data => {
        app.globalData.openId = data.openId
        app.globalData.isItineraryInfoByOpenId = data.isItineraryInfoByOpenId
        if (app.globalData.isItineraryInfoByOpenId == true&&!app.globalData.switchId) {
          this.getItineraryCodeNew()
        }
      }
    } 
    */

  },


  onShow() {
    let that = this
    wx.login({
      success: ports => {
        that.setData({
          code: ports.code
        })
      }
    })
    that.setData({
      disabled: false
    })
  },
  onUnload(){

  },
  // 系统隐私政策的弹出框
  xtzc:function(){
    this.setData({
      showconfirm:true
    })
  },
  // 系统隐私政策确认框
  conform:function(){
    this.setData({
      showconfirm:false
    })
  },
  ok: function () {
    let that = this
    
    if (that.data.isCheckbox == false) {
      wx.showToast({
        title: '请确认授权行程信息',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.phone == '') {
      wx.showToast({
        title: '请先授权手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.showCode == true) {
      if (that.data.list.length > 1) {
        that.setData({
          showList: true
        })
      } else {
        that.getItineraryCode()
      }
    } else {
      that.isHealthCodeAndItineraryInfo()
    }
  },
  okInfo: function () {
    let that = this
    if (that.data.personNumber == '') {
      wx.showToast({
        title: '请先选择本人身份证',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let xm = that.data.name
    let sfzh = that.data.personNumber
    // 身份证
    if (sfzh) {
      if (sfzh.length == 18) {
        sfzh = sfzh.substring(0, 6) + '********' + sfzh.substring(14, 18)
      } else if (sfzh.length == 15) {
        sfzh = sfzh.substring(0, 4) + '********' + sfzh.substring(11, 15)
      } else {
        let num = sfzh.length - 4
        let str = ''
        for (let index = 0; index < num; index++) {
          str += '*'
        }
        sfzh = sfzh.substring(0, 4) + str
      }
    }
    // 姓名
    if (xm) {
      if (xm.length > 3) {
        xm = that.changeStr(xm, 0, '*')
        xm = that.changeStr(xm, 1, '*')
      } else {
        xm = that.changeStr(xm, 0, '*')
      }
    }
    if (xm == null) {
      xm = '无'
    }
    wx.showModal({
      title: '提示',
      content: `确定[${xm}|${sfzh}]是您本人信息?`,
      success(res) {
        if (res.confirm) {
          that.getItineraryCode()
        }
      }
    })
  },
  // 根据身份证号判断是否有健康码
  getHealthCodeByPersonNumberRest(e) {
    let that = this
    Request.get('/weChat/getHealthCodeByPersonNumberRest', //调用方法
      {
        phone: that.data.phone,
        personNumber: that.data.personNumberNew == '' ? that.data.personNumber : that.data.personNumberNew,
      }, {
      'content-type': 'application/json', // 默认值
    },
    ).then(res => { //成功回调
      if (res.data.success == true) {
        let resData = JSON.parse(res.data.data.data)
        if (resData.success == true) {
          if (resData.data == true) {
            that.getVerificationCode()
            that.setData({
              showCode: true,
              isHealthCode: true
            })
          } else {
            that.setData({
              errInfo: true,
              errInfoTitle: true,
              errText: '返回'
            })
          }
        }

      }
    }).catch(err => { }) //异常回调
  },
  // 获取行程码，跳转页面
  getItineraryCode: function (e) {
    let that = this
    if (that.data.isItinerary == false && that.data.verificationCode == '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    that.getScreenBrightness()
    Request.get('/weChat/getItineraryCodeNew', //调用方法
      {
        appId: appid,
        personNumber: that.data.personNumberNew == '' ? that.data.personNumber : that.data.personNumberNew,
        openId: app.globalData.openId,
        phone: that.data.phone,
        verificationCode: that.data.verificationCode,
        isItinerary: that.data.isItinerary
      }, {
      'content-type': 'application/json', // 默认值
    },
    ).then(res => { //成功回调
      console.log(res);
      console.log("点身份修正");

      if (res.data.success == true) {
        console.log(JSON.parse(res.data.data));
        if (res.data.data && JSON.parse(res.data.data).success == true) {
          let data = encodeURIComponent(res.data.data);
          wx.redirectTo({
            url: '../result/result?data=' + data + '&luminance=' + that.data.luminance,
          })
        } else {
          if (JSON.parse(res.data.data).message == '验证码错误') {
            wx.showToast({
              title: JSON.parse(res.data.data).message,
              icon: 'none',
              duration: 2000
            })
            if (that.data.isHealthCode == false) {
              that.setData({
                verificationCode: '',
              })
              return
            }
          } else if (JSON.parse(res.data.data).message == '健康码数据不存在') {
            that.setData({
              phone: '',
              errInfoTitle: true,
              errText: '返回'
            })
            return
          } else {
            console.log(JSON.parse(res.data.data));
            wx.showToast({
              title: '核验失败,请重试',
              icon: 'none',
              duration: 2000
            })
            this.setData({
              phone: '',
              disabled: false
            })
          }
        }
        that.setData({
          showCode: false,
          isCheckbox: true,
          errInfo: false,
          isItinerary: '',
          verificationCode: '',
          list: [],
          showList: false,
          personNumber: '',
          personNumberNew: '',
        })

      }
    }).catch(err => { }) //异常回调
  },
  // 获取手机验证码
  getVerificationCode: function () {
    let that = this
    Request.get('/weChat/getVerificationCodeNew', //调用方法
      {
        phone: that.data.phone,
      }, {
      'content-type': 'application/json', // 默认值
    },
    ).then(res => { //成功回调
      if (res.data.success == true) {
        if (that.data.isHealthCode == true && that.data.list.length > 0) {
          that.setData({
            showCode: true
          })
        } else {
          that.setData({
            errInfo: true,
            healthCodeButton: false,
          })
        }
        if (JSON.parse(res.data.data).success == true) {
          wx.showToast({
            title: JSON.parse(res.data.data).data,
            icon: 'none',
            duration: 2000
          })
        } else {
          if (JSON.parse(res.data.data).message == '您的验证码仍在有效期内') {
            if (that.data.isHealthCode == true && that.data.list.length > 0) {
              that.setData({
                showCode: true
              })
            } else {
              that.setData({
                healthCodeButton: false,
                errInfo: true
              })
            }
          }
          wx.showToast({
            title: JSON.parse(res.data.data).message,
            icon: 'none',
            duration: 2000
          })
        }

      }
    }).catch(err => { }) //异常回调
  },


  // 是否有申领过健康码和登记行程
  isHealthCodeAndItineraryInfo: function () {
    let that = this
    console.log(this.data.phone);
    Request.get('/weChat/isHealthCodeAndItineraryInfo', //调用方法
      {
        phone: that.data.phone,
      }, {
      'content-type': 'application/json', // 默认值
    },
    ).then(res => { //成功回调
      
      if (res.data.success == true) {
        let resData = JSON.parse(res.data.data)
        if (resData.success == true) {
          that.setData({
            isHealthCode: resData.data.isHealthCode,
            isItinerary: resData.data.isItinerary
          })
          let list = []
          for (const key in resData.data.healthCodeData) {
            list.push(resData.data.healthCodeData[key])
          }
          that.setData({
            list: list,
          })
          if (list.length > 1) {
            if (that.data.isItinerary == true) {
              that.setData({
                showList: true,
              })
            } else {
              this.getVerificationCode()
            }
          } else if (list.length == 1) {
            that.setData({
              personNumber: list[0].sfzh,
            })
            if (that.data.isItinerary == true) {
              that.getItineraryCode()
            } else {
              if (resData.data.isHealthCode == false) {
                that.getHealthCodeByPersonNumberRest()
              } else {
                that.getVerificationCode()
              }
            }
          } else {
            if (resData.data.isHealthCode == false) {
              that.setData({
                errInfo: true
              })
            }
          }

        }
      }
    }).catch(err => { }) //异常回调
  },

  // 微信绑定手机号
  getPhoneNumber: function (e) {
    let that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      Request.post('/weChat/bindPhone', //调用方法
        {
          appId: appid,
          code: that.data.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        }, {
        'content-type': 'application/json', // 默认值
      },
      ).then(res => { //成功回调
        wx.login({
          success: ports => {
            that.setData({
              code: ports.code
            })
          }
        })
        if (res.data.success == true) {
          that.setData({
            phone: res.data.data,
            disabled: true
          })
        } else {
          wx.showToast({
            title: '获取异常，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      }).catch(err => {
        wx.login({
          success: ports => {
            that.setData({
              code: ports.code
            })
          }
        })
      }) //异常回调
    }
  },
  // 根据openID判断是否有今日行程数据
  getItineraryCodeNew() {
    let that = this
    wx.showLoading({
      title: '获取默认行程中',
      icon: 'loading',
      mask: true,
    })
    wx.request({
      method: 'get',
      url: baseUrl + '/weChat/getItineraryCodeNew',
      data: {
        openId: app.globalData.openId,
        appId: appid,
        isItinerary: true,
        phone: '',
        personNumber: '',
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log("点身份修正");
        if (res.data.success == true) {
          if (res.data.data && JSON.parse(res.data.data).success == true) {
            let data = encodeURIComponent(res.data.data);
            wx.redirectTo({
              url: '../result/result?data=' + data + '&luminance=' + that.data.luminance,
            })
            wx.hideLoading()
          }
        }
      },
      fail(err) {
        wx.hideLoading()
      }
    })
  },



  // 健康码核验
  okHealthCode() {
    if (this.data.personNumberNew == '') {
      wx.showToast({
        title: '请输入身份证',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.getHealthCodeByPersonNumberRest()
  },
  // 双码核验
  okDiCode() {
    if (this.data.personNumberNew == '') {
      wx.showToast({
        title: '请输入身份证',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.verificationCode == '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.getItineraryCode()
  },
  changeStr(str, index, changeStr) {
    return str.substr(0, index) + changeStr + str.substr(index + changeStr.length);
  },
  // 身份证输入框
  personNumberInput(e) {
    this.setData({
      personNumberNew: e.detail.value
    })
  },
  // 返回
  okErrBack: function () {
    this.setData({
      isCheckbox: true,
      phone: '',
      verificationCode: '',
      errInfo: false,
      isItinerary: '',
      showCode: false,
      errInfoTitle: false,
      errText: '确定',
      personNumber: '',
      personNumberNew: '',
    })
  },
  // 返回
  okRet() {
    this.setData({
      showList: false
    })
  },
  // 返回
  back(e) {
    this.setData({
      isCheckbox: true,
      // phone: '',
      verificationCode: '',
      errInfo: false,
      isItinerary: '',
      showCode: false,
      errInfoTitle: false,
      errText: '确定',
      personNumber: '',
      personNumberNew: '',
    })
    wx.navigateBack()
  },
  // 验证码输入框
  verificationCodeInput(e) {
    this.setData({
      verificationCode: e.detail.value
    })
  },
  // 多身份证选择
  radioChange(e) {
    for (const iterator of this.data.list) {
      if (iterator.sfzh == e.detail.value) {
        this.setData({
          personNumber: iterator.sfzh,
          name: iterator.xm,
        })
      }
    }

  },
  // 授权选择
  checkboxChange(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        isCheckbox: true
      })
    } else {
      this.setData({
        isCheckbox: false
      })
    }
  },
  // 手机号输入框
  phoneInput(e) {
    if (e.detail.value != this.data.phone) {
      this.setData({
        phone: e.detail.value,
        isCheckbox: true,
        verificationCode: '',
        errInfo: false,
        isItinerary: '',
        showCode: false,
      })
    }

  },
  // 获取屏幕亮度
  getScreenBrightness() {
    let that = this
    wx.getScreenBrightness({
      success(res) {
        if (res.errMsg == 'getScreenBrightness:ok') {
          that.setData({
            luminance: res.value
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
